<template>
    <el-form ref="addResourceFormRef" :rules="resourceData.form_rules" :model="resourceData.form" label-width="140px">
        <el-form-item label="资源名称" size="large" prop="resourceName">
            <el-input size="large" v-model="resourceData.form.resourceName" placeholder="请输入资源名称"></el-input>
        </el-form-item>
        <el-form-item label="资源类型" prop="resourceType">
            <el-radio-group v-model="resourceData.form.resourceType" @change="resourceTypeRadioHandler">
                <el-radio label="2" size="small">菜单/组件</el-radio>
                <el-radio label="1" size="small">目录</el-radio>
                <el-radio label="4" size="small">页面</el-radio>
                <!-- <el-radio label="3" size="small">页面元素/按钮</el-radio> -->
            </el-radio-group>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId">
            <template #label>
                上级菜单
                <el-popover placement="top" :width="200" effect="dark" content="上级菜单只能选择目录类型，默认为一级。">
                    <template #reference>
                        <el-icon style="margin-top: 9px; margin-left: 5px;">
                            <QuestionFilled />
                        </el-icon>
                    </template>
                </el-popover>
            </template>
            <el-tree-select node-key="resourceId" clearable :default-expanded-keys="defaultExpandedKeys"
                :check-strictly="true" v-model="resourceData.form.parentId" :data="parentMenuArray"
                @change="menuChangeHandler" :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="组件/路由" prop="routerName">
            <el-input size="large" v-model="resourceData.form.routerName" placeholder="请输入组件名称/路由名称"></el-input>
        </el-form-item>
        <el-form-item label="菜单路由url" prop="routerPath">
            <el-input size="large" v-model="resourceData.form.routerPath" placeholder="请输入菜单路由url"></el-input>
        </el-form-item>
        <el-form-item v-if="resourceData.form.resourceType==='2' || resourceData.form.resourceType === '4'" label="映射组件路径" prop="component">
            <el-input size="large" v-model="resourceData.form.component" placeholder="请输入映射组件路径"></el-input>
        </el-form-item>
        <el-form-item v-if="resourceData.form.resourceType==='1'" label="映射组件路径" prop="directoryComponent">
            <el-input size="large" disabled v-model="resourceData.directoryComponent" placeholder="请输入映射组件路径"></el-input>
        </el-form-item>
        <el-form-item label="资源描述" prop="description">
            <el-input size="large" v-model="resourceData.form.description" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
            <template #label>
                图标
                <el-popover placement="top" :width="500" effect="dark">
                    <template #reference>
                        <el-icon style="margin-top: 9px; margin-left: 5px;">
                            <QuestionFilled />
                        </el-icon>
                    </template>
                    <div slot="content">
                        <p>请输入以下链接中图标所对应的名称，如想使用搜索图标则输入Search：</p>
                        <a style="color: #409eff" target="_blank"
                            href="https://element-plus.gitee.io/zh-CN/component/icon.html#%E5%9B%BE%E6%A0%87%E9%9B%86%E5%90%88">element-plus图标集合</a>
                    </div>
                </el-popover>
            </template>
            <el-input size="large" v-model="resourceData.form.icon" placeholder="请输入图标代码"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
            <template #label>
                排序
                <el-popover placement="top" :width="200" effect="dark" content="数字越大，排序越靠前。">
                    <template #reference>
                        <el-icon style="margin-top: 9px; margin-left: 5px;">
                            <QuestionFilled />
                        </el-icon>
                    </template>
                </el-popover>
            </template>
            <el-input-number size="large" v-model="resourceData.form.sort" placeholder=""></el-input-number>
        </el-form-item>



        <el-form-item v-if="resourceData.permissionShow" label="页面功能" prop="permissionElementArray">
            <el-row :gutter="10">
                <el-col :span="9">元素标识</el-col>
                <el-col :span="9">权限编码</el-col>
                <el-col :span="4">操作</el-col>
            </el-row>
            <el-row :gutter="10" v-for="(item, index) in resourceData.permissionElementArray" :key="index">
                <el-col :span="9"><el-input v-model="item.permissionElement" size="small" /></el-col>
                <el-col :span="9"><el-input v-model="item.permissionCode" size="small" /></el-col>
                <el-col :span="4"><el-button size="small" @click="pageElementItemDel(index)">删除</el-button></el-col>
            </el-row>
            <el-button type="primary" text size="small" @click="pageElementItemAdd">添加功能</el-button>
        </el-form-item>



        <el-form-item>
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>

import { ref, reactive, getCurrentInstance } from 'vue';

// ElementUI 单独引入
import { ElMessage } from 'element-plus'

// api
import { addResource } from "@/api/permission"

const { proxy } = getCurrentInstance();

const props = defineProps({
    menuPermissionData: Array,
    defaultExpandedKeys: Array
})

const emit = defineEmits(["addResult"])


// 所有下拉菜单
const parentMenuArray = props.menuPermissionData
// 需要默认展开的菜单
const defaultExpandedKeys = props.defaultExpandedKeys


const resourceData = reactive({
    form: {
        resourceName: "",
        description: "",
        parentId: '',
        resourceType: '2',
        routerName: '',
        routerPath: '',
        component: '',
        sort: 0
    },
    directoryComponent: 'App.vue',
    form_rules: {
        resourceName: [
            {
                required: true,
                message: "请输入资源名称",
                trigger: 'blur'
            }
        ],
        routerName: [
            {
                required: true,
                message: "请输入组件路由",
                trigger: 'blur'
            }
        ],
        routerPath: [
            {
                required: true,
                message: "请输入菜单路由url",
                trigger: 'blur'
            }
        ],
        component: [
            {
                required: true,
                message: "请输入映射组件路径",
                trigger: 'blur'
            }
        ]
    },
    // 页面元素数组
    permissionElementArray: [],
    // 页面元素显示标识
    permissionShow: true
})

// 页面元素项
const permissionElementItem = {
    permissionElement: "",
    permissionCode: ""
}

// 增加页面元素项
const pageElementItemAdd = () => {
    for (let item in resourceData.permissionElementArray) {
        if (resourceData.permissionElementArray[item].permissionElement === "" ||
            resourceData.permissionElementArray[item].permissionCode === "") {
            ElMessage({
                message: "请把功能选项填写完整再添加。",
                type: "error"
            })
            return
        }
    }
    resourceData.permissionElementArray.push(JSON.parse(JSON.stringify(permissionElementItem)));
}

// 删除页面元素项
const pageElementItemDel = (index) => {
    // console.log("点击了index", index)
    resourceData.permissionElementArray.splice(index, 1);
}

// 资源类型改变事件
const resourceTypeRadioHandler = (val) => {
    if ((val === "1" || val === "4") && resourceData.permissionShow) {
        resourceData.permissionShow = !resourceData.permissionShow
    } else if (val === "2" && !resourceData.permissionShow) {
        resourceData.permissionShow = !resourceData.permissionShow
    }
    resourceData.form.resourceType = val
}


// 上级菜单选择触发事件
const menuChangeHandler = (val) => {
    console.log("触发了：", val)
    resourceData.form.parentId = val
}

// 提交保存
const submitForm = () => {
    let requestData = resourceData.form
    if ((requestData.resourceType === "2" || requestData.resourceType === "4") &&
        (requestData.parentId === null || requestData.parentId === '')) {
        ElMessage({
            message: "请选择上级菜单。",
            type: "error"
        })
        return
    }
    if (requestData.parentId === null || requestData.parentId === '') {
        requestData.parentId = 0
    }
    proxy.$refs.addResourceFormRef.validate(async (valid) => {
        if (!valid) {
            return;
        }
        requestData.pageElementList = []
        for (let item in resourceData.permissionElementArray) {
            if (resourceData.permissionElementArray[item].permissionElement === "" ||
                resourceData.permissionElementArray[item].permissionCode === "") {
                ElMessage({
                    message: "请把功能选项填写完整再添加。",
                    type: "error"
                })
                return
            }
            requestData.pageElementList.push(resourceData.permissionElementArray[item])
        }
        const data = await addResource(requestData)
        console.log("结果：", data)
        if (data.code !== 200) {    // 添加不成功
            return
        } else {
            ElMessage({
                message: data.msg,
                type: "success"
            })
            // 重置表单
            resetForm()
            // 通知父组件
            emit('addResult' , 1)
            return;
        }
    })

}

// 表单重置
const resetForm = () => {
    proxy.$refs.addResourceFormRef.resetFields()
}

</script>

<style scoped lang="scss"></style>